{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import argparse\n",
    "import os\n",
    "import pickle\n",
    "import random\n",
    "import signal\n",
    "import warnings\n",
    "from collections import defaultdict\n",
    "from itertools import permutations\n",
    "from random import shuffle\n",
    "\n",
    "import multitasking\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "max_threads = multitasking.config['CPU_CORES']\n",
    "multitasking.set_max_threads(max_threads)\n",
    "multitasking.set_engine('process')\n",
    "signal.signal(signal.SIGINT, multitasking.killall)\n",
    "\n",
    "random.seed(2020)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mms(df):\n",
    "    user_score_max = {}\n",
    "    user_score_min = {}\n",
    "\n",
    "    # 获取用户下的相似度的最大值和最小值\n",
    "    for user_id, g in df[['user_id', 'sim_score']].groupby('user_id'):\n",
    "        scores = g['sim_score'].values.tolist()\n",
    "        user_score_max[user_id] = scores[0]\n",
    "        user_score_min[user_id] = scores[-1]\n",
    "\n",
    "    ans = []\n",
    "    for user_id, sim_score in tqdm(df[['user_id', 'sim_score']].values):\n",
    "        ans.append((sim_score - user_score_min[user_id]) /\n",
    "                   (user_score_max[user_id] - user_score_min[user_id]) +\n",
    "                   10**-3)\n",
    "    return ans\n",
    "\n",
    "\n",
    "def recall_result_sim(df1_, df2_):\n",
    "    df1 = df1_.copy()\n",
    "    df2 = df2_.copy()\n",
    "\n",
    "    user_item_ = df1.groupby('user_id')['article_id'].agg(set).reset_index()\n",
    "    user_item_dict1 = dict(zip(user_item_['user_id'],\n",
    "                               user_item_['article_id']))\n",
    "\n",
    "    user_item_ = df2.groupby('user_id')['article_id'].agg(set).reset_index()\n",
    "    user_item_dict2 = dict(zip(user_item_['user_id'],\n",
    "                               user_item_['article_id']))\n",
    "\n",
    "    cnt = 0\n",
    "    hit_cnt = 0\n",
    "\n",
    "    for user in user_item_dict1.keys():\n",
    "        item_set1 = user_item_dict1[user]\n",
    "\n",
    "        cnt += len(item_set1)\n",
    "\n",
    "        if user in user_item_dict2:\n",
    "            item_set2 = user_item_dict2[user]\n",
    "\n",
    "            inters = item_set1 & item_set2\n",
    "            hit_cnt += len(inters)\n",
    "\n",
    "    return hit_cnt / cnt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_click = pd.read_pickle('./user_data/data/offline/click.pkl')\n",
    "df_query = pd.read_pickle('./user_data/data/offline/query.pkl')\n",
    "\n",
    "recall_path = './user_data/data/offline'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "recall_methods = ['itemcf', 'w2v', 'binetwork']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  0%|                                                                                      | 0/8946303 [00:00<?, ?it/s]D:\\evo\\anaconda\\envs\\tf1.14\\lib\\site-packages\\ipykernel_launcher.py:14: RuntimeWarning: invalid value encountered in double_scalars\n",
      "  \n",
      "100%|████████████████████████████████████████████████████████████████████| 8946303/8946303 [00:28<00:00, 311093.05it/s]\n",
      "100%|████████████████████████████████████████████████████████████████████| 4523450/4523450 [00:14<00:00, 310947.00it/s]\n",
      "  0%|                                                                                      | 0/4448665 [00:00<?, ?it/s]D:\\evo\\anaconda\\envs\\tf1.14\\lib\\site-packages\\ipykernel_launcher.py:14: RuntimeWarning: invalid value encountered in double_scalars\n",
      "  \n",
      "100%|████████████████████████████████████████████████████████████████████| 4448665/4448665 [00:14<00:00, 314384.00it/s]\n"
     ]
    }
   ],
   "source": [
    "weights = {'itemcf': 1, 'binetwork': 1, 'w2v': 0.1}\n",
    "recall_list = []\n",
    "recall_dict = {}\n",
    "for recall_method in recall_methods:\n",
    "    recall_result = pd.read_pickle(\n",
    "            f'{recall_path}/recall_{recall_method}.pkl')\n",
    "    weight = weights[recall_method]\n",
    "\n",
    "    recall_result['sim_score'] = mms(recall_result)\n",
    "    recall_result['sim_score'] = recall_result['sim_score'] * weight\n",
    "\n",
    "    recall_list.append(recall_result)\n",
    "    recall_dict[recall_method] = recall_result\n",
    "\n",
    "    # 求相似度\n",
    "for recall_method1, recall_method2 in permutations(recall_methods, 2):\n",
    "    score = recall_result_sim(recall_dict[recall_method1],\n",
    "                                  recall_dict[recall_method2])\n",
    "\n",
    "    # 合并召回结果\n",
    "recall_final = pd.concat(recall_list, sort=False)\n",
    "recall_score = recall_final[['user_id', 'article_id',\n",
    "                                 'sim_score']].groupby([\n",
    "                                     'user_id', 'article_id'\n",
    "                                 ])['sim_score'].sum().reset_index()\n",
    "\n",
    "recall_final = recall_final[['user_id', 'article_id', 'label'\n",
    "                                 ]].drop_duplicates(['user_id', 'article_id'])\n",
    "recall_final = recall_final.merge(recall_score, how='left')\n",
    "\n",
    "recall_final.sort_values(['user_id', 'sim_score'],\n",
    "                             inplace=True,\n",
    "                             ascending=[True, False])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████████████████████████████████████████████████████████████████████| 90469/90469 [00:43<00:00, 2076.91it/s]\n"
     ]
    }
   ],
   "source": [
    "# 删除无正样本的训练集用户\n",
    "gg = recall_final.groupby(['user_id'])\n",
    "useful_recall = []\n",
    "\n",
    "for user_id, g in tqdm(gg):\n",
    "    if g['label'].isnull().sum() > 0:\n",
    "        useful_recall.append(g)\n",
    "    else:\n",
    "        label_sum = g['label'].sum()\n",
    "        if label_sum > 1:\n",
    "            print('error', user_id)\n",
    "        elif label_sum == 1:\n",
    "            useful_recall.append(g)\n",
    "\n",
    "df_useful_recall = pd.concat(useful_recall, sort=False)\n",
    "\n",
    "\n",
    "df_useful_recall = df_useful_recall.sort_values(\n",
    "        ['user_id', 'sim_score'], ascending=[True,\n",
    "                                             False]).reset_index(drop=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df_useful_recall['user_id'].value_counts().reset_index()\n",
    "df.columns = ['user_id', 'cnt']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_useful_recall.to_pickle('./user_data/data/offline/recall.pkl')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:tf1.14]",
   "language": "python",
   "name": "conda-env-tf1.14-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
